/**
 * 
 */
package org.dragonfire.editor.z80.hiliteRules;

import org.dragonfire.editor.AttributeManager;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.swt.SWT;

/**
 * @author Darth Android
 * @date Oct 2, 2007
 */
public class DirectiveRule implements IRule {

	static {
		AttributeManager.addAttribute("asm.syntax.directive", 0, 0, 128, SWT.BOLD);
	}
	public static final String DIRECTIVE_START_CHARS = "#.";
	private IToken token;

	public DirectiveRule() {
		token = new Token(AttributeManager.getAttribute("asm.syntax.directive"));
	}

	public IToken evaluate(ICharacterScanner scanner) {
		if (scanner.getColumn() != 0)
			return Token.UNDEFINED;
		return evaluate(scanner, false);
	}

	public IToken evaluate(ICharacterScanner scanner, boolean seenText) {
		int i = scanner.read();
		if (i == ICharacterScanner.EOF) {
			scanner.unread();
			if (seenText)
				return token;
			return Token.UNDEFINED;
		}
		char c = (char) i;
		IToken t = Token.UNDEFINED;
		if (Character.isWhitespace(c) && !seenText)
			t = evaluate(scanner, false);
		if (seenText) {
			if (!Character.isWhitespace(c))
				t = evaluate(scanner, true);
			else {
				scanner.unread();
				t = token;
			}
		}
		else if (DIRECTIVE_START_CHARS.contains("" + c))
			t = evaluate(scanner, true);
		if (t == Token.UNDEFINED)
			scanner.unread();
		return t;
	}
}
